from datetime import datetime

from elasticsearch_dsl import (
    Document,
    Keyword,
    Long,
    Text,
    Float,
    Nested,
    Date,
    Join,
    Object,
    Short,
    Boolean,
    connections,
    analyzer, InnerDoc,
)

from config import settings
from core.es import Index_KJJ_ACTIVITY_REGISTER

connections.create_connection(hosts=[settings.dsl], timeout=80)

en_lowercase = analyzer(
    "en_name_analyzer",
    tokenizer="standard",
    filter=["lowercase", "stop", "snowball"],
)


class Dept(InnerDoc):
    """
    科协部门
    """

    id = Text(fielddata=True)
    institution_name =Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word",
                         position_increment_gap=100)
    is_kexie = Boolean()


class Base(Document):
    activity_member = Join(relations={"activity": "member"})
    update_at = Date(required=True)  # for es

    class Index:
        name = Index_KJJ_ACTIVITY_REGISTER
        settings = {
            "number_of_shards": 1,
            "number_of_replicas": 0,
        }

    def save(self, **kwargs):
        # if there is no date, use now
        return super().save(**kwargs)


class Activity(Base):
    name = Text(fields={"keyword": Keyword(ignore_above=256)}, position_increment_gap=100, required=True)
    start_time = Date()
    abstract = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer=en_lowercase, position_increment_gap=100)
    end_time = Date()
    host_label = Object(Dept, required=True)
    coop_labels = Nested(Dept)  # 数组
    images = Keyword()  # 数组
    videos = Keyword()  # 数组
    activity_type = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word",
                         position_increment_gap=100)
    importance_of_activities = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word",
                                    position_increment_gap=100)
    activity_type_two = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word",
                             position_increment_gap=100)
    # 地区
    region = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word", position_increment_gap=100)
    province = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word", position_increment_gap=100)
    city = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word", position_increment_gap=100)
    district = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word", position_increment_gap=100)
    number_of_applicants = Long()
    update_time = Date()
    score_importance_of_activities = Long()  # 活动分
    range_year = Short()  # 活动聚类年份

    activity_tags = Keyword()

    def save(self, **kwargs):
        self.activity_member = "activity"
        self.meta.routing = 1
        return super().save(**kwargs)

    def add_member(self, member, commit=True):
        member = Register(
            # required make sure the answer is stored in the same shard
            _routing=1,
            # since we don't have explicit index, ensure same index as self
            _index=self.meta.index,
            # set up the parent/child mapping
            activity_member={"name": "member", "parent": self.meta.id},
            **member
        )
        if commit:
            member.save()
        return member


class Register(Base):
    contribution = Long()
    is_attended = Boolean()
    level_of_role = Text()
    per_act_time = Float()
    role = Text()
    register_time = Date()
    person_id = Text()
    activity_id = Text(fielddata=True)
    act_type = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word", position_increment_gap=100)
    #
    score_importance_of_role = Long()  # 角色分
    score_importance_of_activities = Long()  #活动分

    def save(self, **kwargs):
        # set routing to parents id automatically
        self.meta.routing = 1
        return super().save(**kwargs)


def setup():
    """Create an IndexTemplate and save it into elasticsearch."""
    index_template = Base._index.as_template("base")
    index_template.save()


if __name__ == "__main__":
    # initiate the default connection to elasticsearch
    # create index
    setup()
    Base.init()
